<template>
  <el-dialog
    :title="`物流商渠道运输方式管理`"
    width="80%"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div v-loading="loading">
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :disabled="disabled"
        @submit="handleSearch"
        @reset="handleSearch"
      >
        <template #create_user="{ value, input }">
          <VCascader
            :model-value="value"
            @update:model-value="input"
            collapse-tags
            style="width: 200px"
            placeholder="创建人"
          />
        </template>
      </VForm>
      <div class="my-[8px]">
        <VActionBar :actions="actions" />
      </div>
      <vxe-grid
        ref="tableRef"
        v-bind="tableOptions"
        class="custom-tooltip-table"
      />
    </div>

    <!-- <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
      </div>
    </template> -->
  </el-dialog>
  <Log
    dialog
    v-model="logVisible"
    :autoLoad="false"
    tag="logistics.api-shipping"
    :business_id="logId"
    @close="logId = ''"
  />
  <AddShipping
    :id="id"
    v-model="visible"
    @refresh="handleRefresh"
    @close="id = ''"
  />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import Log from "@/components/Log/index.vue";
import VForm from "@/components/Form/index.vue";
import AddShipping from "./AddShipping/index.vue";
import DerivedCenter from "@/components/DerivedCenter";
import { getTableSelectRowOld } from "@/hooks/tool.js";
import {
  logisticsShipping,
  logisticsShippingStatus,
  logisticsShippingSync,
} from "../../api";
import { config_name } from "@/config/export.js";
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  apiId: { type: [String, Number], default: "" },
  apiName: { type: String, default: "" },
});

const { proxy } = getCurrentInstance();

const emit = defineEmits(["update:modelValue", "refresh", "close"]);

const formOption = {
  inline: true,
  labelPosition: "top",
  option: true,
  showResetButton: true,
};

const form = ref();
const tableRef = ref();

const id = ref();
const model = ref({});
const loading = ref(false);
const logVisible = ref(false);
const logId = ref("");
const visible = ref(false);

const publicStyle = { style: { width: "150px" } };
const fieldList = [
  { field: "api_name", ...publicStyle, placeholder: "物流商API名称" },
  { field: "api_ident", ...publicStyle, placeholder: "物流商API标识" },
  {
    field: "status",
    style: { width: "100px" },
    type: "select",
    options: {
      placeholder: "状态",
      data: [
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 },
      ],
    },
  },
  {
    field: "create_user",
    slot: "create_user",
    type: "select",
    options: { placeholder: "创建人" },
  },
  { field: "cn_name", placeholder: "物流商渠道运输方式中文名", ...publicStyle },
  { field: "use_code", placeholder: "运输方式代码", ...publicStyle },
  {
    field: "shipping_type",
    style: { width: "180px" },
    placeholder: " 运输方式类型",
  },
];

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      if (!props.modelValue) return;
      nextTick(() => {
        handleRefresh();
      });
    }
  }
);
watch(
  () => props.apiName,
  (val) => {
    if (val) {
      nextTick(() => {
        model.value.api_name = val;
      });
      // console.log(val);
      // model.value.api_name = val;
      // console.log(model.value);
    }
  }
);
const tableOptions = reactive({
  pagerConfig: { pageSize: 20 },
  round: true,
  height: "500",
  columnConfig: {
    resizable: true,
  },
  showOverflow: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { fixed: "left", width: 50, title: "编号", type: "seq" },
    {
      fixed: "left",
      title: "物流商API名称",
      width: 120,
      field: "api_name",
    },
    { title: "物流商API标识", width: 120, field: "api_ident" },
    { title: "物流商渠道运输方式中文名", width: 220, field: "cn_name" },
    { title: "物流商渠道运输方式英文名", width: 220, field: "en_name" },
    { title: "运输方式代码", width: 105, field: "use_code" },
    { title: "运输方式类型", width: 120, field: "shipping_type" },
    { title: "状态", width: 120, field: "status_text" },
    { title: "备注", width: 200, field: "remark" },
    { title: "创建人", width: 170, field: "create_user" },
    { title: "创建时间", width: 170, field: "create_time" },
    {
      title: "操作",
      width: 180,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-button link type="primary" onClick={() => handleEdit(row.id)}>
                编辑
              </el-button>
              <el-button
                link
                type={row.status === 0 ? "primary" : "danger"}
                onClick={() =>
                  handleStatusReq(row.id, row.status === 0 ? 1 : 0)
                }
              >
                {{ 0: "启用", 1: "禁用" }[row.status]}
              </el-button>
              <el-button link type="primary" onClick={() => handleLog(row)}>
                日志
              </el-button>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page }) => {
        const { apiId, apiName } = props || {};
        return logisticsShipping({
          api_name: apiName,
          ...model.value,
          ...page,
          logistics_api_id: apiId,
        });
      },
    },
  },
});

const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};

const handleEdit = (_id) => {
  id.value = _id;
  visible.value = true;
};

const getSelectRows = () => {
  const rows = tableRef.value?.getCheckboxRecords();
  if (!rows?.length) {
    ElMessage({
      showClose: true,
      message: "请至少选择一条数据！",
      type: "warning",
    });
    return [];
  }
  return rows;
};

const handleStatus = (status) => {
  const rows = getSelectRows();
  if (!rows.length) return;
  const id = rows.map((n) => n.id);
  handleStatusReq(id, status);
};

const handleStatusReq = (id, flag) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认{flag ? "启用" : "禁用"}选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await logisticsShippingStatus({ id, status: flag ? 1 : 0 });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          handleRefresh();
        }
      } else {
        done();
      }
    },
  });
};

const handleRefresh = () => {
  nextTick(() => {
    tableRef.value?.commitProxy("reload");
  });
};

const handleSearch = (form) => {
  model.value = form;
  nextTick(() => {
    handleRefresh();
  });
};

//导出中心
const DerivedCenterRef = ref();
const handleExport = () => {
  let condition = getTableSelectRowOld(tableRef.value, model.value);
  DerivedCenterRef.value?.open({
    tag_name: config_name["logistics_settings"]["logistics_api_shipping"],
    condition,
  });
};

const handleSync = () => {
  loading.value = true;
  try {
    const { code, message, data } = logisticsShippingSync({ id: props?.apiId });
    // if (code !== 200) {
    //  ElMessage.warning(message)
    //  return
    // }
    loading.value = false;
    ElMessage.success("正在同步中,请稍后查看!");
    // ElMessage.success(`${message},同步数量:${data?.countTotal||0},成功数量:${data?.countSuccess||0},失败数量:${data?.countFail||0}`)
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const handleClose = async (refresh) => {
  model.value = {};
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
const actions = [
  {
    label: "新增",
    icon: "add2",
    type: "primary",
    fn: () => (visible.value = true),
  },
  {
    label: "启用",
    icon: "state_finish_line",
    fn: () => handleStatus(true),
  },
  {
    label: "禁用",
    icon: "state_disabled",
    fn: () => handleStatus(false),
  },
  {
    label: "导出",
    dkicon: "icon-Upload",
    fn: handleExport,
  },
  {
    label: "同步",
    fn: handleSync,
    show: () => props?.apiId,
  },
];
</script>
<style lang="scss" scoped>
.form-components{
  padding-top: 7px;
  padding-bottom: 2px;
}
</style>
